#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<iostream>
#include <unistd.h>
#include<memory>
#include <pthread.h>
#include "Mutex.hpp"
using namespace MutexModule;

//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

class ThreadDate{
    public:
    ThreadDate() = default;
    ThreadDate(const std::string &n,Mutex& _lock)
    {
        name = n;lock = &_lock;
    }
    ~ThreadDate(){}

    std::string name;
    Mutex *lock;
};

int ticket = 1000;
void *route(void *arg)
{
    std::unique_ptr<ThreadDate> *id = (std::unique_ptr<ThreadDate> *)arg;
    while (1)
    {
        //(*id)->lock->Lock();
        //pthread_mutex_lock(&mutex);
        Guard a((*id)->lock);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", (*id)->name.c_str(), ticket);
            ticket--;
            //pthread_mutex_unlock(&mutex);
            //(*id)->lock->UnLock();
        }
        else
        {
            //(*id)->lock->UnLock();
            //pthread_mutex_unlock(&mutex);   
            break;
        }
    }
    return nullptr;
}

int main(void)
{
    Mutex lock;
    pthread_t t1, t2, t3, t4;
    std::unique_ptr<ThreadDate> td1 = std::make_unique<ThreadDate>("thread 1",lock);
    pthread_create(&t1, NULL, route, &td1);
    //pthread_mutex_init(&mutex, NULL);
    std::unique_ptr<ThreadDate> td2 = std::make_unique<ThreadDate>("thread 2",lock);
    pthread_create(&t2, NULL, route, &td2);
    std::unique_ptr<ThreadDate> td3 = std::make_unique<ThreadDate>("thread 3",lock);
    pthread_create(&t3, NULL, route, &td3);
    std::unique_ptr<ThreadDate> td4 = std::make_unique<ThreadDate>("thread 4",lock);
    pthread_create(&t4, NULL, route, &td4);
    // pthread_create(&t1, NULL, route, (void *)"thread 1");
    // pthread_create(&t2, NULL, route, (void *)"thread 2");
    // pthread_create(&t3, NULL, route, (void *)"thread 3");
    // pthread_create(&t4, NULL, route, (void *)"thread 4");

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);
    //pthread_mutex_destroy(&mutex);
    return 0;
}